package com.mjf.cjt.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.chanjet.openapi.sdk.java.exception.ChanjetApiException;
import com.mjf.cjt.domain.TmDepartmentDicEntity;
import com.mjf.cjt.mapper.TmDepartmentDicMapper;
import com.mjf.cjt.service.AsyncTMService;
import com.mjf.cjt.service.TmDepartmentDicService;
import com.mjf.cjt.vo.DepartResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/4/13 21:13
 */
@Service
public class TmDepartmentDicServiceImpl extends ServiceImpl<TmDepartmentDicMapper, TmDepartmentDicEntity> implements TmDepartmentDicService {

    @Autowired
    private AsyncTMService asyncTMService;


    @Override
    @Transactional
    public void syncDepart() {
        try {
            List<DepartResultVO> vos = asyncTMService.syncDepart();
            if (CollectionUtil.isNotEmpty(vos)) {
                List<TmDepartmentDicEntity> entities = new ArrayList<>();
                for (DepartResultVO row : vos) {
                    TmDepartmentDicEntity entity = new TmDepartmentDicEntity();
                    BeanUtil.copyProperties(row, entity);
                    if (row.getParent() != null) {
                        entity.setParentcode(row.getParent().getCode());
                        entity.setParentname(row.getParent().getName());
                    }
                    entities.add(entity);
                }
                saveOrUpdateBatch(entities);
            }
        } catch (ChanjetApiException e) {
            throw new RuntimeException(e);
        }
    }
}
